import { SearchOutlined } from '@ant-design/icons'
import { message, Input } from 'antd'
import { ReactComponent as AllQywxIcon } from '@/desktop/assets/all-qywx.svg'
import { Actionable } from '@/desktop/components'
import { ChooseAccountModal } from '@/desktop/components/ChooseAccount'
import useQywxList from '@/desktop/logics/qywx/list'
import useQywxNotify from '@/desktop/logics/qywx/notify'
import { useQywxUnreads } from '@/desktop/logics/qywx/unreads'
import { colors } from '@/desktop/styles'
import { SiderItem } from '@/desktop/views/app'
import { panelSubject as appPanelSubject } from '@/desktop/views/app/cover-panel'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { BaseAccount } from '@/services/auth'
import { type QywxInfo, type QywxStatusInfo } from '@/services/qywxs'

import { AddQywxTrigger } from './add'
import { BatchAction } from './batch-action'
import { QywxItem } from './item'
import { RescanModal } from './rescan'
import { commonS } from './styles'

export function Qywxs(props: { collapsed: boolean }) {
  const { collapsed } = props

  const [account] = useStreams(services.auth.account$)
  const accountId = account?.id ?? ''

  useQywxNotify()

  const [search, setSearch] = useState('')
  const {
    qywxs,
    filteredQywxs,
    normalQywxs,
    preparingQywxs,
    focused,
    logout,
    transfer,
    focus,
    cancelFocus,
  } = useQywxList({
    search: collapsed ? '' : search,
  })
  const unreads = useQywxUnreads(focused?.wxid ?? null)

  const [transfering, setTransfering] = useState<QywxInfo[] | null>(null)
  const finishTransfer = useCallback(() => setTransfering(null), [])
  const submitTransfer = useCallback(
    async ([target]: [BaseAccount]) => {
      if (!transfering) return
      const res = await transfer(transfering, target.id, target.name)
      if (res === true) {
        setTransfering(null)
        void message.success('转交成功')
      } else {
        void message.error(`转交失败：${res}`)
      }
    },
    [transfering, transfer],
  )

  const [choosing, setChoosing] = useState<string | null>(null) // string: 正在“多选”，此字符串为初始要选中的 wxid

  const itemLogout = useCallback((wxid: string) => logout([wxid]), [logout])
  const itemStartTransfer = useCallback((qywx: QywxInfo) => setTransfering([qywx]), [])
  const itemStartChoose = useCallback((wxid: string) => setChoosing(wxid), [])
  const finishChoose = useCallback(() => setChoosing(null), [])

  function showAll() {
    cancelFocus()
    appPanelSubject.next(null) // 若有内容面板处于开启状态，点此按钮也会将其关闭，保证能看到聊天界面
  }

  function renderQywxItem(qywx: QywxStatusInfo) {
    return <QywxItem
      key={qywx.wxid}
      qywx={qywx}
      unread={unreads?.get(qywx.wxid)}
      collapsed={collapsed}
      focused={focused?.wxid === qywx.wxid}
      focus={focus}
      cancelFocus={cancelFocus}
      logout={itemLogout}
      startTransfer={itemStartTransfer}
      startChoose={itemStartChoose}
    />
  }

  return <div css={styles.wrap}>
    {qywxs.length >= 1 ? (
      <div css={styles.count}>
        <span>已登录</span>
        <span>{qywxs.length}个</span>
      </div>
    ) : null}

    <div css={styles.search}>
      <Input
        value={search}
        onChange={e => setSearch(e.target.value)}
        placeholder="搜索企业微信"
        prefix={<SearchOutlined />}
        allowClear
      />
    </div>

    <SiderItem
      css={[commonS.siderItem, { marginBottom: '16px' }]}
      collapsed={collapsed}
      icon={<AllQywxIcon />}
      title="全部聊天"
      tooltip="查看全部聊天"
      onClick={showAll}
    />

    {filteredQywxs.length ? (
      <div css={styles.list}>
        {normalQywxs.map(renderQywxItem)}

        {preparingQywxs.length ? (
          <div css={styles.preparings} className={collapsed ? 'collapsed' : ''}>
            <h5>{collapsed ? '初始化中' : '首次登录初始化中'}</h5>
            {preparingQywxs.map(renderQywxItem)}
          </div>
        ) : null}
      </div>
    ) : null}

    <Actionable strict>
      <AddQywxTrigger collapsed={collapsed} />
    </Actionable>

    <ChooseAccountModal
      visible={!!transfering}
      title="选择转交到的账号"
      onCancel={finishTransfer}
      onChoosed={submitTransfer}
      disabled={accountId}
    />

    <BatchAction
      qywxs={qywxs}
      initialChoosed={choosing}
      startTransfer={setTransfering}
      logout={logout}
      onCancel={finishChoose}
    />

    <RescanModal />
  </div>
}

const hideOnCollapsed = css`
  overflow: hidden;
  transition:
    height 0.2s,
    margin-bottom 0.2s;
  .ant-layout-sider-collapsed & {
    height: 0;
    margin-bottom: 0;
    opacity: 0;
  }
`

const styles = {
  wrap: css`
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
  `,

  count: css`
    ${hideOnCollapsed};
    color: ${colors.gray};
    display: flex;
    flex-shrink: 0;
    height: 1em;
    justify-content: space-between;
    line-height: 1;
    margin-bottom: 23px;
    padding: 0 15px;
    white-space: nowrap;
  `,

  search: css`
    ${hideOnCollapsed};
    flex-shrink: 0;
    height: 34px;
    margin-bottom: 20px;
    padding: 0 15px;
    .ant-input-affix-wrapper {
      border: none;
      padding-bottom: 6px;
      padding-top: 6px;
    }
    .ant-input-prefix {
      color: ${colors.gray};
      font-size: 18px;
      margin-right: 10px;
    }
  `,

  list: css`
    flex-grow: 0;
    margin-bottom: 16px;
    margin-top: -8px;
    padding-top: 8px; // 给未读消息角标留一点空间
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 0;
    }
  `,
  preparings: css`
    &:not(:first-of-type) {
      margin-top: 12px;
    }
    & > h5 {
      color: ${colors.gray};
      font-weight: normal;
      margin-bottom: 8px;
      padding-left: 11px;
    }
    &.collapsed h5 {
      text-align: center;
      padding-left: 0;
    }
  `,
}
